package com.atom.app.mvi.ui.compose

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Surface
import androidx.compose.material.TextField
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import kotlinx.coroutines.delay

/**
 * https://www.cnblogs.com/guanxinjing/p/16787401.html
 *
 */
class StateComposeActivity : ComponentActivity() {
    /**
     *  remember：保存数据，并且在UI更新时会提供保存的值。但是Activity页面退出后会丢失保存的值
    rememberSaveable：保存数据，并且将值写入到bundle中，然后重新构建Activity的时候，从bundle读数据。这表示Activity退出后也不会丢失值。
    mutableStateOf ：一个可变并且被Compose时刻观察的状态存储，作用就是让Compose可以获知数据已经改变，UI上的内容需要重新绘制。
    mutableStateListOf：mutableStateOf只能观察单个类型数据的变化，无法观察到集合数据的变化。所以有了mutableStateListOf，方法参数带vararg关键字，所以它也可以是多个List组成的数组
    mutableStateMapOf：同上，只不过是以哈希的形式，方法参数带vararg关键字，所以它也可以是数组
    derivedStateOf：定义的对象状态依赖其他的对象状态时，需要使用derivedStateOf，当依赖对象状态发生改变，自己也可以跟着改变。

    remember是用于临时保存数据的，而MutableState是用于通知与传递数据变化的。
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { RememberAndMutableStateOf_Demo() }
    }

    @Preview(name = "add")
    @Composable
    fun PreviewMessageCard() {
        DerivedStateOf_Demo()
    }

    @Composable
    fun RememberAndMutableStateOf_Demo() {
        Surface(
            modifier = Modifier.fillMaxSize()
        ) {
            Column(
                modifier = Modifier.fillMaxSize()
            ) {
                var count1 by remember { mutableStateOf(0) }
                Text(text = "count1 $count1")
                Button(onClick = { count1++ }) {
                    Text(text = "count1")
                }
                var count2 = remember { mutableStateOf(0) }
                Text(text = "count2 ${count2.value}")
                Button(onClick = { count2.value++ }) {
                    Text(text = "count2")
                }

                var (count3, setValue) = remember { mutableStateOf(0) }
                Text(text = "count3 ${count3}")
                Button(onClick = { setValue.invoke(count3 + 1) }) {
                    Text(text = "count3")
                }
            }
        }

    }

    var mImageList = mutableStateListOf<String>()
    @Composable
    fun MutableStateListOf_Demo() {
        mImageList.apply {
            this.add(" 1 ")
            this.add(" 2 ")
            this.add(" 3 ")
            this.add(" 4 ")
            this.add(" 5 ")
            this.add(" 6 ")
            this.add(" 7 ")
            this.add(" 8 ")
            this.add(" 9 ")
            this.add(" 10 ")
        }
        Surface(
            modifier = Modifier.fillMaxSize()
        ) {
            LazyVerticalGrid(
                columns = GridCells.Adaptive(minSize = 256.dp),
                verticalArrangement = Arrangement.spacedBy(20.dp),
                horizontalArrangement = Arrangement.spacedBy(20.dp),
                contentPadding = PaddingValues(top = 20.dp, start = 20.dp, end = 20.dp)
            ) {
                items(mImageList.size) { index ->
                    Column {
                        Text(text = " >> ${mImageList[index]}")
                        Button(onClick = { /*TODO*/ }) {
                            Text(text = "------------------------------------")
                        }
                        AsyncImage(model = mImageList[index],
                            contentDescription = null,
                            contentScale = ContentScale.Crop,
                            modifier = Modifier
                                .width(256.dp)
                                .height(128.dp)
                                .pointerInput(Unit) {
                                    detectTapGestures(onTap = {
                                        mImageList.add(
                                            0,
                                            "${mImageList[index]} click ${System.currentTimeMillis()}"
                                        )
                                    }, onLongPress = {
                                        mImageList.add(
                                            0,
                                            "${mImageList[index]} onlongclick ${System.currentTimeMillis()}"
                                        )
                                    })
                                }
                                .clip(RoundedCornerShape(10.dp)))
                    }
                }
            }
        }
    }

    @Composable
    fun MutableStateMapOf_Demo() {
        val dataMap = remember {
            mutableStateMapOf(
                "key1" to "value1", "key2" to "value2", "key3" to "value3", "key4" to "value4"
            )
        }
        Surface(
            modifier = Modifier.fillMaxSize()
        ) {
            LazyVerticalGrid(
                columns = GridCells.Adaptive(minSize = 256.dp),
                verticalArrangement = Arrangement.spacedBy(20.dp),
                horizontalArrangement = Arrangement.spacedBy(20.dp),
                contentPadding = PaddingValues(top = 20.dp, start = 20.dp, end = 20.dp)
            ) {
                items(dataMap.size) { index ->
                    Column {
                        val value = dataMap.keys.toMutableList()[index]
                        Text(text = " >> ${value}")
                        Button(onClick = { /*TODO*/ }) {
                            Text(text = "------------------------------------")
                        }
                        AsyncImage(model = value,
                            contentDescription = null,
                            contentScale = ContentScale.Crop,
                            modifier = Modifier
                                .width(256.dp)
                                .height(128.dp)
                                .pointerInput(Unit) {
                                    detectTapGestures(onTap = {
                                        dataMap.put(value, value + " >> ")
                                    }, onLongPress = {
                                        dataMap.put(value, value + " >> ")
                                    })
                                }
                                .clip(RoundedCornerShape(10.dp)))
                    }
                }
            }
        }
    }

    @Composable
    fun DerivedStateOf_Demo() {
        var count by remember {
            print("asdasdads 1")
            mutableStateOf(0)
        }
        val isOdd by remember {
            print("asdasdads 2")
            derivedStateOf { count % 2 != 0 }
        }
        Surface(modifier = Modifier) {
            Column {
                Text(text = "Count : ${count} isOdd : ${isOdd}")
                Button(onClick = { count++ }) {
                    Text(text = "Add")
                }
            }
        }
    }
    @Composable
    fun MyTextField() {
        val text = remember {
            mutableStateOf("")
        }
        MyLaunchedEffect(content = text.value)
        Column {
            TextField(value = text.value, onValueChange = {
                text.value = it
            })
        }
    }

    @Composable
    fun MyLaunchedEffect(content:String){
        Log.e("zh", "MyLaunchedEffect重组中 content = ${content}")
        LaunchedEffect(Unit){
            while (true){
                delay(500)
                Log.e("zh", "content = ${content}")
            }
        }
    }
}